import elu.base.model as model
from sqlalchemy.sql import text


class ParameterModel:
    def __init__(self, tablename):
        self.engine = model.engine
        self.meta = model.meta
        self.tablename = tablename
        self.table = self.meta.tables[tablename]

    def c(self, name):
        raw = "SELECT * FROM %s WHERE name=%r" % (self.tablename, name)
        inspect = self.engine.execute(raw)
        inspect_result = [dict(row) for row in inspect]

        if len(inspect_result) > 0:
            result = 'duplicate'
        else:
            raw_nd = "INSERT INTO %s (name) VALUES (%r)" % (self.tablename, name)
            self.engine.execute(raw_nd)
            result = 'success'

        return result

    def r(self):
        raw = "SELECT * FROM %s" % self.tablename
        result = self.engine.execute(raw)
        return [dict(row) for row in result]

    def d(self, name):
        raw = "DELETE FROM %s WHERE id=%r" % (self.tablename, name)
        self.engine.execute(raw)

        raw_nd = "SELECT * FROM %s WHERE id=%r" % (self.tablename, name)
        inspect = self.engine.execute(raw_nd)
        inspect_result = [dict(row) for row in inspect]

        if len(inspect_result) > 0:
            result = 'fail'
        else:
            result = 'success'

        return result


class ParameterPersonnelModel:
    def __init__(self):
        self.engine = model.engine
        self.meta = model.meta
        self.table = self.meta.tables['supp_personnel']

    def c(self, workno, name, domain, position):
        raw = "SELECT * FROM supp_personnel WHERE workno=%r AND domain=%r" % (workno, domain)
        inspect = self.engine.execute(raw)
        inspect_result = [dict(row) for row in inspect]

        if len(inspect_result) > 0:
            result = 'duplicate'
        else:
            raw_nd = "INSERT INTO supp_personnel (workno, name, domain, position) VALUES (%r, %r, %r, %r)" \
                     % (workno, name, domain, position)
            self.engine.execute(raw_nd)
            result = 'success'

        return result

    def u(self):
        pass

    def r(self):
        raw = "SELECT * FROM supp_personnel"
        result = self.engine.execute(raw)
        return [dict(row) for row in result]

    def d(self, iden):
        raw = "DELETE FROM supp_personnel WHERE id=%r" % (iden)
        self.engine.execute(raw)

        raw_nd = "SELECT * FROM supp_personnel WHERE id=%r" % (iden)
        inspect = self.engine.execute(raw_nd)
        inspect_result = [dict(row) for row in inspect]

        if len(inspect_result) > 0:
            result = 'fail'
        else:
            result = 'success'

        return result